package org.xg.study.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.Principal;

/**
 * @author CMG
 * @version 1.0
 * @description
 * @cLassName DoServlet
 * @date 2021/9/24 10:27
 **/
@WebServlet("/doServlet")
public class DoServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter printWriter = resp.getWriter();
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String sex = req.getParameter("sex");
        String city = req.getParameter("city");
        String[] languages = req.getParameterValues("username");
        String code = req.getParameter("code");

        Boolean isSuccess = true;
        String code1 = (String) getServletContext().getAttribute("code");
        if (!"".equals(code) && null != code && code.equalsIgnoreCase(code1) && "admin".equals(username) &&
                "admin".equals(password)) {
            resp.sendRedirect("/ServletRed/success");
        } else if (!"admin".equals(username) || !"admin".equals(password)) {
            getServletContext().setAttribute("msg", "账号或密码不正确");
            isSuccess = false;
        } else if ("".equals(code) || null == code || !code.equals(code1)) {
            getServletContext().setAttribute("msg", "验证码输入错误");
            isSuccess = false;
        }
        if (!isSuccess) {
            //设置自动跳转的时间，存储在上下文中
            getServletContext().setAttribute("time", 5);
            req.setAttribute("requestAttr", "重定向中使用request域对象传递数据");
            resp.sendRedirect("/ServletRed/refresh");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
